<template>
  <el-dialog :title="product_info.name + ' Api参数'" top="10vh" :visible.sync="isShow" width="90%" style="overflow-y: scroll;">
    <div class="table_content" style="min-height: 68vh">
      <div class="from-title">
        <span>参数</span>
        <div>
          <el-button type="primary" size="mini" @click="addRootNode">增加</el-button>
          <el-button type="primary" size="mini" @click="onSaveSend">保存</el-button>
        </div>
      </div>
      <!-- v-if="!table_loading"  -->
      <div class="table">
        <el-table
          v-loading="table_loading"
          :data="treeData"
          row-key="id"
          border
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column
            prop="key"
            label="参数名"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.key" size="mini" style="width: 160px;" />
            </template>
          </el-table-column>

          <el-table-column
            prop="type"
            label="类型"
            width="150"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.type" size="mini" placeholder="类型" :disabled="scope.row.children.length>0">
                <el-option label="string" value="string" />
                <el-option label="number" value="number" />
                <el-option label="boolean" value="boolean" />
                <!-- <el-option label="array" value="array" /> -->
                <el-option label="object" value="object" />
                <el-option label="null" value="null" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="type"
            label="方法"
            width="160"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.func" size="mini" placeholder="方法" filterable>
                <el-option v-for="item in funOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column
            prop="value"
            label="示例值"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" size="mini" :disabled="scope.row.type == 'object'" />
            </template>
          </el-table-column>

          <el-table-column
            prop="key"
            label="操作"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                :disabled="scope.row.type != 'object'"
                type="primary"
                size="mini"
                @click="addChildNode(scope.row.id)"
              >增加</el-button>
              <el-button size="mini" @click="deleteNodeAndChildren(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

      </div>

    </div>

  </el-dialog>
</template>

<script>
import {
  getProuduceApi,
  updateProuduceApi
} from '@/api/apiCommon'
import { setTimeout } from 'core-js'
import { getStorageSync } from '@/utils/storageUtils.js'

export default {
  name: 'JsonTree',
  data() {
    return {
      isShow: false,
      table_loading: false,
      product_info: {},
      funOptions: [],
      treeData: []
    }
  },
  created() {
    const commonOptionData = getStorageSync('config_current', false)
    this.funOptions = commonOptionData.request_config.func || []
  },
  updated() {
    setTimeout(() => {
      this.table_loading = false
    }, 50)
  },
  methods: {
    // 定义一个函数，用于递归地为树形数据的每个节点分配唯一的ID
    assignUniqueIds(nodes, startingId = 1) {
      const _this = this
      _this.table_loading = true
      let currentId = startingId

      // 递归函数用于为每个节点分配ID并递增currentId
      function assignId(node) {
        node.id = currentId++ // 为节点分配ID
        if (node.children && node.children.length) {
          node.children.forEach(child => assignId(child)) // 递归子节点
        }
      }
      nodes.forEach(node => assignId(node)) // 为每个节点分配ID
      // console.log('新树形ids', nodes)
      return nodes // 返回更新后的节点数组
    },

    // 根节点增加数据
    addRootNode() {
      const _this = this
      _this.treeData.push({
        id: null,
        key: '',
        type: 'object',
        value: '',
        func: 'not',
        children: []
      })
      // 重新自动分配id
      _this.assignUniqueIds(_this.treeData)
    },
    // 添加子节点
    addChildNode(parentId) {
      const _this = this
      const parentDepartment = _this.findNodeById(_this.treeData, parentId)
      if (parentDepartment) {
        parentDepartment.children.push({
          id: null,
          key: '',
          type: 'object',
          value: '',
          func: 'not',
          children: []
        })
        // 重新自动分配id
        _this.assignUniqueIds(_this.treeData)
      }
    },
    findNodeById(nodes, id) {
      const _this = this
      for (const node of nodes) {
        if (node.id === id) {
          return node
        }
        if (node.children) {
          const childNode = _this.findNodeById(node.children, id)
          if (childNode) {
            return childNode
          }
        }
      }
      return null
    },

    // 删除节点
    deleteNodeAndChildren(nodeId) {
      const _this = this
      function deleteNode(nodes) {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === nodeId) {
            nodes.splice(i, 1)
            return true
          }
          if (nodes[i].children && deleteNode(nodes[i].children)) {
            return true
          }
        }
        return false
      }
      return deleteNode(_this.treeData)
    },

    // 列表请求
    onOpenView(data) {
      const _this = this
      _this.isShow = true
      _this.table_loading = true
      if (data?.id) {
        _this.product_info = Object.assign(_this.product_info, data)
        getProuduceApi({ product_id: data.id })
          .then((response) => {
            const result = response.data
            this.treeData = result.content || []
          }).finally(() => {
            _this.table_loading = false
          })
      }
    },

    onSaveSend() {
      // console.log(JSON.stringify(this.treeData))
      updateProuduceApi({
        product_id: this.product_info.id,
        content: JSON.stringify(this.treeData)
      }).then((response) => {
        if (response.code === 1) {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.coloseDailog()
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
        }
      })
    },
    coloseDailog() {
      this.isShow = false
      this.product_info = {}
      this.treeData = []
    }
  }
}
</script>

<style lang="scss" scoped>
.from-title{
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
  color: #333;
}
</style>
